package com.cavy.platform.server.domain.message;

import com.cavy.platform.server.domain.AgentOnline;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @author 唐旭
 * @Date 2018/7/24
 */
public abstract class AbstractMessageHandlerImpl<T extends Message> implements MessageHandler {
    @Override
    public boolean support(String type) {
        return getTypeClass().getSimpleName().equalsIgnoreCase(type);
    }

    protected abstract Class<T> getTypeClass();

    @SuppressWarnings("unchecked")
    @Override
    public void handler(Session session, String message, AgentOnline agent) {
        Class<T> typeClass = getTypeClass();
        ObjectMapper mapper = new ObjectMapper();
        try {
            T o = mapper.readValue(message, typeClass);
            handler(session, o, agent);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected abstract void handler(Session session, T message, AgentOnline agent);
}
